<template>
  <section class="todoapp">
    <TodoHeader :list="newList" @addItem="addItemFn"></TodoHeader>
    <TodoMain
      :list="item"
      @delItem="delItemFn"
      v-for="item in newList"
      :key="item.id"
    >
    </TodoMain>
    <TodoFooter
      :list="newList"
      @changeType="changeTypeFn"
      @delDone="delDoneFn"
    ></TodoFooter>
  </section>
</template>

<script>
import TodoMain from "./components/TodoMain.vue";
import TodoHeader from "./components/TodoHeader.vue";
import TodoFooter from "./components/TodoFooter.vue";
import "./styles/base.css";
import "./styles/index.css";

// 样式引入 + 导入组件并注册使用
export default {
  components: {
    TodoMain,
    TodoHeader,
    TodoFooter,
  },

  data() {
    return {
      // list: [
      //   {
      //     id: 100,
      //     name: "吃饭",
      //     isDone: true,
      //   },
      //   {
      //     id: 201,
      //     name: "睡觉",
      //     isDone: false,
      //   },
      //   {
      //     id: 103,
      //     name: "打豆豆",
      //     isDone: true,
      //   },
      // ],
      list: JSON.parse(localStorage.getItem("todoList")) || [],
      type: "allList",
    };
  },

  methods: {
    addItemFn(content) {
      this.list.push({
        id: +new Date(),
        name: content,
        isDone: false,
      });
    },
    changeTypeFn(type) {
      this.type = type;
    },
    delItemFn(id) {
      this.list = this.list.filter((item) => item.id !== id);
    },

    delDoneFn() {
      this.list = this.list.filter((item) => !item.isDone);
    },
  },

  computed: {
    newList() {
      if (this.type === "allList") {
        return this.list;
      } else if (this.type === "NoDoneList") {
        return this.list.filter((item) => !item.isDone);
      } else if (this.type === "DoneList") {
        return this.list.filter((item) => item.isDone);
      }
    },
  },

  watch: {
    list: {
      deep: true,
      handler() {
        localStorage.setItem("todoList", JSON.stringify(this.list));
      },
    },
  },
};
</script>
